package com.ipay.wechat.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ipay.foreign.pojo.MerchantPayParameter;
import com.ipay.foreign.service.MerchantPayParameterService;
import com.ipay.utils.*;
import com.ipay.wechat.component.Wechat;
import com.ipay.wechat.pojo.*;
import com.ipay.wechat.service.*;

import net.sf.json.JSONArray;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import com.ipay.redis.JedisExecutor;
import com.ipay.redis.JedisKeyPrefix;
import com.ipay.wechat.util.Utils;

import net.sf.json.JSONObject;

@Controller
public class UserMangerController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private JedisExecutor jedisManager;
    @Autowired
    private CashiersService cashiersService;
    @Autowired
    private ApplyService applyService;
    @Autowired
    private QRCodeService codeService;
    @Autowired
    private UserWechatInfoService uwiService;
    @Autowired
    private LoginService loginService;
    @Autowired
    private QRCodeService qRCodeService;
    @Autowired
    private PayChannelService payChannelService;
    @Autowired
    private BankInfoService bankInfoService;
    @Autowired
    private MerchantInfoService merchantInfoService;
    @Autowired
    private MerchantPayParameterService merchantPayParameterService;
    @Autowired
    private JedisExecutor jedies;
    @Autowired
    private Wechat wechat;

    /**
     * 判断 是否登录
     *
     * @param request
     * @param map
     * @return
     */
    @SuppressWarnings("unused")
    @RequestMapping("/auth/isMerchant")
    public ModelAndView isMerchant(HttpServletRequest request, ModelMap map) {
        String openid = (String) request.getSession().getAttribute("openid");
        //----上线注释掉---begin---
        if (StringUtil.isBlank(openid)) {
            openid = "oejR50ugUxEvsvfyzR5dHfZv_8Mk";
            //openid = "oejR50lPUQq5eRVL31sSIyEo0Ybg";
            request.getSession().setAttribute("openid", openid);
        }
        //----上线注释掉---end---
        if (StringUtil.isEmpty(openid)) {
            return new ModelAndView("login.jsp");
        }
        //查询商户信息表中是否有数据
        MerchantInfo merchant = applyService.querryInfoByOpenid(openid);
        //根据openid查询微信用户表
        UserWechatInfo wechat = uwiService.findOneByOpenidInUserWX(openid);
        if (wechat == null) {//不是微信用户，进入登录页面
            if (merchant != null) {
                if (merchant.getStatus() == 0) {//已审核
                    map.put("status", 0); //未审核
                    return new ModelAndView("apply/applysuccess1.jsp");
                }
            } else {
                return new ModelAndView("login.jsp");
            }
        } else {
            //根据openid查询登录表
            WechatLogin login = loginService.findWechatLoginByOpenid(openid);
            if (login == null || login.getStatus() == 0) {//第一次登陆或者为未登录
                return new ModelAndView("login.jsp");
            } else { //已登陆
                //根据手机号和状态为激活 查询收款员表中是否有数据
                Cashiers cashiers = cashiersService.findCashierByMobileAndState(login.getMobilephone(), Constant.Status.ENABLE.getValue()); //已激活
                if (cashiers != null) { //将之前的用户强制退出
                    request.getSession().removeAttribute("openid");
                    request.getSession().removeAttribute("merchant");
                    request.getSession().removeAttribute("wechat");
                    request.getSession().removeAttribute("cashiers");
                    request.getSession().removeAttribute("nickname");
                    request.getSession().removeAttribute("headimgurl");

                    map.put("merchant", merchant);//商户信息
                    map.put("cashiers", cashiers);  //用户信息
                    map.put("wechat", wechat);
                    //map.put("openid", openid);
                    request.getSession().setAttribute("openid", openid);

                    //根据收款员id查询二维码列表
                    List<QRCode> codeList = codeService.findQRCodeByUserId(cashiers.getId(), cashiers.getMerchantId());
                    if (codeList.size() > 0) {
                        map.put("codeList", codeList);
                    }
                    return new ModelAndView("user_center.jsp");
                /*} else if (cashiers != null&&StringUtil.isNotEmpty(cashiers.getActivateState())&& cashiers.getActivateState() == 0) {
                    request.getSession().setAttribute("mobilephone", login.getMobilephone());     //商户手机号码
                    return new ModelAndView("register.jsp");*/
                }
            }
        }
        return new ModelAndView("login.jsp");
    }

    /**
     * 员工管理
     *
     * @param request
     */
    @ResponseBody
    @RequestMapping(value = "/auth/viewCashierList")
    public ModelAndView viewCashierList(HttpServletRequest request, ModelMap map) {
        String openid = (String) request.getSession().getAttribute("openid");
        if (StringUtil.isEmpty(openid)) {//第一次登陆或者为未登录
            return new ModelAndView("login.jsp");
        }
        MerchantInfo merchant = applyService.querryInfoByOpenid(openid);
        if (merchant != null) {
            List<Cashiers> cashierslist = cashiersService.findCashierList(merchant.getMerchantNo(), merchant.getMerchantId());
            logger.info("收款员数量：" + cashierslist.size());
            map.put("cashierslist", cashierslist);
            map.put("merchant", merchant);
        }
        return new ModelAndView("employee.jsp");
    }

    /**
     * 查看商铺基本资料
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/auth/viewMerInfo")
    public ModelAndView viewMerInfo(HttpServletRequest request, ModelMap map) {
        String openid = (String) request.getSession().getAttribute("openid");
        //根据openid查询登录表
        WechatLogin login = loginService.findWechatLoginByOpenid(openid);
        if (login != null) {
            //根据手机号查询收款员表商户编号
            Cashiers cashiers = cashiersService.findCashierByMobileAndState(login.getMobilephone(), Constant.Status.ENABLE.getValue()); //已激活
            if (cashiers != null) {
                //根据收款员表商户编号查询商户信息
                MerchantInfo merchant = applyService.querryMerchantInfoByMerchantNo(cashiers.getMerchantId());
                map.put("merchant", merchant);
            }
        }
        return new ModelAndView("/shop_info.jsp");
    }

    /**
     * 查看签约信息
     *
     * @return
     */
    @RequestMapping(value = "/auth/viewSignInfo")
    public ModelAndView viewSignInfo(HttpServletRequest request, ModelMap map) {
        String openid = (String) request.getSession().getAttribute("openid");
        //根据openid查询登录表
        WechatLogin login = loginService.findWechatLoginByOpenid(openid);

        if (login != null) {
            //根据手机号查询收款员表商户编号
            Cashiers cashiers = cashiersService.findCashierByMobileAndState(login.getMobilephone(), Constant.Status.ENABLE.getValue()); //已激活
            if (cashiers != null) {
                //查询支付渠道表费率
                Map<String, Object> mapPayChannel = new HashMap<String, Object>();
                mapPayChannel.put("merchantNo", cashiers.getMerchantId());
                mapPayChannel.put("payState", Constant.Status.ENABLE.getValue());//状态 0、删除 1、启用 2、禁用
                mapPayChannel.put("payType", Constant.PayType.PAY_WX.getValue());
                PayChannelEntity paychannelwechant = payChannelService.queryPayBymerchantNo(mapPayChannel);//微信
                mapPayChannel.put("payType", Constant.PayType.PAY_ZFB.getValue());
                String wechantPayRate = "未设置";
                if (paychannelwechant != null) {
                    wechantPayRate = StringUtil.isNotEmptyValue(paychannelwechant.getPayRate(), "未设置").toString();
                }
                PayChannelEntity paychannelpay = payChannelService.queryPayBymerchantNo(mapPayChannel);//微信
                String payRate = "未设置";
                if (paychannelpay != null) {
                    payRate = StringUtil.isNotEmptyValue(paychannelpay.getPayRate(), "未设置").toString();
                }
                map.put("wechantPayRate", wechantPayRate); //微信
                map.put("PayRate", payRate);     //支付宝
            }
        }
        return new ModelAndView("sign_info.jsp");
    }

    /**
     * 查看收款码
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/auth/viewQRCode")
    public ModelAndView viewQRCode(HttpServletRequest request, ModelMap map) {
        logger.info("viewQRCode");
        String openid = (String) request.getSession().getAttribute("openid");
        if (StringUtil.isEmpty(openid)) {//第一次登陆或者为未登录
            return new ModelAndView("login.jsp");
        }
        MerchantInfo merchant = applyService.querryInfoByOpenid(openid);
        /*//如果是收款员，则只能查看自己的收款
        List<QRCode> list = null;
        if (merchant != null && StringUtil.isNotEmpty(merchant.getMerchantNo())) {
            if (merchant.getRole() == 2) { //查询收款员的二维码信息
                list = codeService.findQRCodeByUserId(merchant.getCashiersId(), merchant.getMerchantNo());
            } else {
                QRCode code=new QRCode();
                code.setMerchantId(merchant.getMerchantNo());
                code.setMid(merchant.getMerchantId());
                list = codeService.findQRCode(code);
            }
        }
        logger.info("收款码总数===" + list.size());
        if (list != null && list.size() == 0) {
            map.put("message", "暂无收款码");
        }
        map.put("list", list);*/


        if (merchant != null) {
            map.put("role", merchant.getRole());
            List<Cashiers> cashList = cashiersService.findListByMerchantId(merchant.getMerchantNo());
            if (cashList.size() == 0) {
                map.put("message", "暂无收款码");
            }
            map.put("cashList", cashList);
        }

        //查询商户是否配置了支付参数数据
        boolean bool = false;
        if (merchant != null && StringUtil.isNotEmpty(merchant.getMerchantNo())) {
            Map<String, Object> mapPayChl = new HashMap<String, Object>();
            mapPayChl.put("payState", Constant.Status.ENABLE.getValue());
            mapPayChl.put("merchantNo", merchant.getMerchantNo());
            List<PayChannelEntity> payChannelList = payChannelService.queryList(mapPayChl);
            List<BankInfo> bankInfoList = bankInfoService.queryList(mapPayChl);//查询银行卡是否有启用的
            if (bankInfoList != null && bankInfoList.size() != 0) {
                bool = true;
            }
            map.put("merchantNo", merchant.getMerchantNo());
        }
        map.put("showAddBut", bool);
        return new ModelAndView("/qr_code.jsp");
    }

    /**
     * 固定金额二维码生成入口
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/auth/fixedMoneyQRCode")
    public ModelAndView fixedMoneyQRCode(HttpServletRequest request, ModelMap map) {
        logger.info("****************====：fixedMoneyQRCode");
        String openid = (String) request.getSession().getAttribute("openid");
        if (StringUtil.isEmpty(openid)) {//第一次登陆或者为未登录
            return new ModelAndView("login.jsp");
        }
        MerchantInfo merchant = applyService.querryInfoByOpenid(openid);
        //查询商户是否配置了支付参数数据
        boolean bool = false;
        if (merchant != null && StringUtil.isNotEmpty(merchant.getMerchantNo())) {
            Map<String, Object> mapPayChl = new HashMap<String, Object>();
            mapPayChl.put("payState", Constant.Status.ENABLE.getValue());
            mapPayChl.put("merchantNo", merchant.getMerchantNo());
            List<BankInfo> bankInfoList = bankInfoService.queryList(mapPayChl);//查询银行卡是否有启用的
            if (bankInfoList != null && bankInfoList.size() == 1) {
                map.put("bankInfo", bankInfoList.get(0));
                bool = true;
            }
        }
        map.put("merchant", merchant);
        map.put("showAddBut", bool);
        return new ModelAndView("/auth/fixedMoneyQRCode.jsp");
    }

    /**
     * 固定金额二维码生成处理
     * @param request
     * @param payMoney  金额
     * @param payremark  收款说明
     * @param map
     * @return
     */
    @RequestMapping(value = "/auth/submitFixedMoneyQRCode")
    public ModelAndView submitFixedMoneyQRCode(HttpServletRequest request,@RequestParam String payMoney,@RequestParam String payremark, ModelMap map) {
        logger.info("****************====：fixedMoneyQRCode");
        String openid = (String) request.getSession().getAttribute("openid");
        if (StringUtil.isEmpty(openid)) {//第一次登陆或者为未登录
            return new ModelAndView("login.jsp");
        }
        MerchantInfo merchant = applyService.querryInfoByOpenid(openid);//查询当前登录用户是那个商户
        if(merchant!=null&&StringUtil.isNotEmpty(merchant.getMerchantNo())&&StringUtil.isNotEmpty(merchant.getCashiersId())) {
            //查询当前用户二维码信息
            List<QRCode> codeList = codeService.findQRCodeByUserId(merchant.getCashiersId(), merchant.getMerchantNo());
            if (codeList != null && codeList.size() > 0) {
                QRCode qRCode= codeList.get(0);
                ///保存请求数据
                MerchantPayParameter merchantPay = new MerchantPayParameter();
                merchantPay.setCodeNo(qRCode.getCodeNo());
                merchantPay.setMerchantNo(merchant.getMerchantNo());
                merchantPay.setPayMoney(new BigDecimal(payMoney));
                merchantPay.setPayremark(payremark);
                merchantPay.setTypes(Constant.TYPES_GDJEEWM);//发起类型（0第三方pc端，1收款员生成固额二维码）
                merchantPayParameterService.save(merchantPay);
                //merchantPay = merchantPayParameterService.queryObject("11");
                map.put("merchantPay", merchantPay);
                map.put("qrcode", qRCode);
                return new ModelAndView("/auth/showfixMeyQRCode.jsp");
            }else{
                map.put("errorMesage", "当前用户暂无收款二维码,请联系管理员添加");
                return new ModelAndView("/common/error.jsp");
            }
        }else{
            map.put("errorMesage", "获取用户企业信息错误");
            return new ModelAndView("/common/error.jsp");
        }
    }


    /**
     * 我的账户
     *
     * @param request
     * @param map
     * @return
     */
    @RequestMapping(value = "/auth/viewMyAccount")
    public ModelAndView viewMyAccount(HttpServletRequest request, ModelMap map) {
        String openid = (String) request.getSession().getAttribute("openid");
        if (StringUtil.isEmpty(openid)) {//第一次登陆或者为未登录
            return new ModelAndView("login.jsp");
        }
        //根据openid查询登录表
        WechatLogin login = loginService.findWechatLoginByOpenid(openid);
        if (login != null) {
            //根据手机号查询收款员表商户编号
            Cashiers cashiers = cashiersService.findCashierByMobileAndState(login.getMobilephone(), Constant.Status.ENABLE.getValue()); //已激活
            if (cashiers != null) {
                //根据收款员表商户编号查询商户信息
                MerchantInfo merchant = applyService.querryMerchantInfoByMerchantNo(cashiers.getMerchantId());
                map.put("merchant", merchant);//商户信息
                map.put("cashiers", cashiers);//收款员信息
            }
        }
        return new ModelAndView("myAccount.jsp");
    }

    /**
     * 切换手机号
     *
     * @return
     */
    @RequestMapping(value = "/auth/changeMobile")
    public ModelAndView changeMobile(HttpServletRequest request, ModelMap map) {
        String id = request.getParameter("id");
        map.put("id", id);
        return new ModelAndView("changeMobile.jsp");
    }

    /**
     * 更改手机号
     *
     * @param mobile         手机号
     * @param validationCode 验证码
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/auth/sureChange")
    public R sureChange(@RequestParam String openid, @RequestParam String mobile, @RequestParam String validationCode,
                        @RequestParam Long id, HttpServletRequest request) {
        logger.info("sureChange openid==" + openid + "mobile==" + mobile + " validationCode==" + validationCode
                + " id==" + id);
        String vcode = "666666";
        //String vcode = jedisManager.getValue(JedisKeyPrefix.JEDIS_KEY_PREFIX_MOBILE, mobile);
        System.out.println("sureChange vcode：" + vcode);

        Cashiers cashiers = cashiersService.findCashierByMobile(mobile, Constant.ActivateState.T_DELETED.getValue());
        if (cashiers != null) {
            return R.error("该手机号码已绑定其他用户");
        }

        if (!(validationCode.equals(vcode))) {
            return R.error("验证码不正确");
        }

        Cashiers cash = new Cashiers();
        cash.setMobilephone(mobile);
        cash.setId(id);
        //根据手机号码查询收款员表
        cashiersService.update(cash);//更新收款员信息
        loginService.updateWechatLoginByOpenid(0, mobile, openid);//更新登陆表用户手机号

        return R.ok("修改成功");
    }

    /**
     * @param id       收款员表主键
     * @param isNotify 是否通知 0、否   1、是
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/auth/isNotify")
    public R isNotify(@RequestParam Long id, @RequestParam int isNotify, HttpServletRequest request) {
        boolean flag = cashiersService.updateIsNotify(id, isNotify);
        if (flag) {
            return R.ok("操作成功");
        }
        return R.error("数据错误，操作失败");
    }

    /**
     * 跳转到登陆页面
     */
    @RequestMapping(value = "/auth/login")
    public ModelAndView login(ModelMap map, HttpServletRequest request) {
        //request.getSession().removeAttribute("openid");
        request.getSession().removeAttribute("merchant");
        request.getSession().removeAttribute("wechat");
        request.getSession().removeAttribute("cashiers");
        return new ModelAndView("login.jsp");
    }

    /**
     * 跳转到添加收款码页面
     */
    @RequestMapping(value = "/auth/qrCodePage")
    public ModelAndView qrCodePage(ModelMap map, HttpServletRequest request) {
        String openid = (String) request.getSession().getAttribute("openid");
        if (StringUtil.isEmpty(openid)) {//第一次登陆或者为未登录
            return new ModelAndView("login.jsp");
        }
        MerchantInfo merchant = applyService.querryInfoByOpenid(openid);
        if (merchant != null && StringUtil.isNotEmpty(merchant.getMerchantNo())) {
            //List<Cashiers> cashierslist = cashiersService.findCashierList(merchant.getMerchantNo(), merchant.getMerchantId());
            List<Cashiers> cashierslist = cashiersService.findCashierByMerchantId(merchant.getMerchantNo());
            List<Map> listcashiers = new ArrayList<Map>();
            for (Cashiers cashiers : cashierslist) {
                Map mapbank = new HashMap();
                mapbank.put("title", cashiers.getName() + "/" + cashiers.getMobilephone());
                mapbank.put("value", cashiers.getId());
                listcashiers.add(mapbank);
            }
            JSONArray cashiersjson = JSONArray.fromObject(listcashiers);
            map.put("cashiersStr", cashiersjson);
            map.put("cashierslist", cashierslist);

            //收款账户信息
            Map<String, Object> mapBak = new HashMap<String, Object>();
            mapBak.put("merchantNo", merchant.getMerchantNo());
            mapBak.put("payState", "1");
            List<BankInfo> bankInfoList = bankInfoService.queryList(mapBak);
            List<Map> listbank = new ArrayList<Map>();
            for (BankInfo bankInfo : bankInfoList) {
                Map mapbank = new HashMap();
                mapbank.put("title", bankInfo.getBankName() + "/" + bankInfo.getBankCard());
                mapbank.put("value", bankInfo.getId());
                listbank.add(mapbank);
            }
            JSONArray json = JSONArray.fromObject(listbank);
            map.put("strbuffBankStr", json);
            map.put("bankInfoList", bankInfoList);
        }
        map.put("merchant", merchant); //商户信息
        return new ModelAndView("addQr_code.jsp");
    }

    /**
     * 跳转到收款员页面
     */
    @RequestMapping(value = "/auth/cashierPage")
    public ModelAndView cashierPage(HttpServletRequest request, ModelMap map) {
        String openid = (String) request.getSession().getAttribute("openid");
        if (StringUtil.isEmpty(openid)) {//第一次登陆或者为未登录cashierPage
            return new ModelAndView("login.jsp");
        }
        MerchantInfo merchant = applyService.querryInfoByOpenid(openid);
        List<Map> listbank = new ArrayList<Map>();
        if (merchant != null && StringUtil.isNotEmpty(merchant.getMerchantNo())) {
            Map mapbank = new HashMap();
            mapbank.put("title", merchant.getUsername() + "/" + merchant.getShopname());
            mapbank.put("value", merchant.getMerchantNo());
            listbank.add(mapbank);

            //获取当前用户 一二级商户信息
            Map<String, Object> merchantMap = new HashMap<String, Object>();
            merchantMap.put("id", merchant.getMerchantId());
            List<MerchantInfoEntity> merchantInfoList = merchantInfoService.queryTwoLevelList(merchantMap);
            for (MerchantInfoEntity merchantInfoEntity : merchantInfoList) {
                Map mapbankOth = new HashMap();
                mapbankOth.put("title", merchantInfoEntity.getUsername() + "/" + merchantInfoEntity.getShopName());
                mapbankOth.put("value", merchantInfoEntity.getMerchantNo());
                listbank.add(mapbankOth);
            }
            JSONArray json = JSONArray.fromObject(listbank);
            map.put("merchantInfoStr", json);
            map.put("merchant", merchant);
            map.put("merchantInfoList", merchantInfoList);
        }
        return new ModelAndView("addCashier.jsp");
    }

    /**
     * 确定添加收款员
     *
     * @param mobile
     * @param name
     * @param mobile
     * @param merchantNo
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/auth/addCashier")
    public R addCashier(@RequestParam String name, @RequestParam String mobile, @RequestParam String merchantNo,
                        HttpServletRequest request) {
        Cashiers cashiers = cashiersService.findCashierByMobile(mobile, Constant.ActivateState.T_DELETED.getValue());
        if (cashiers != null) { // 该收款员已关联商铺
            return R.error("手机号已有关联用户");
        } else {
            try {
                MerchantInfo merchant = applyService.querryMerchantInfoByMerchantNo(merchantNo);
                logger.info(merchantNo + "商户信息==merchant" + merchant);
                String mobile_code = RandomStringUtils.randomNumeric(6);
                if (merchant != null) {
                    cashiersService.insertCashier(name, mobile, 0,
                            merchant.getMerchantNo(), 0, 2, mobile_code); //保存收银信息

                    Map<String, String> contentMap = new HashMap<String, String>();
                    contentMap.put("merchant", merchant.getUsername());
                    contentMap.put("shop", merchant.getShopname());
                    contentMap.put("mobile", mobile);
                    contentMap.put("code", mobile_code);
                    JSONObject jsonObject = HttpUtils.getValidCode(mobile, "37717", contentMap);
                    logger.info("发送短信验证码返回结果：" + jsonObject);
                    if (jsonObject != null && jsonObject.getInt("error_code") == 0) { // 发送成功
                        return R.ok("邀请码已发送至该收款员手机，请通知尽快使用");
                    } else {
                        return R.ok("保存成功，但邀请码发送失败");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                return R.error(502, "增加收款员失败");
            }
        }
        return R.error("增加收款员失败");
    }

    /**
     * 删除收款员
     *
     * @param mobilephone 收款员电话
     * @return
     */
    @ResponseBody
    @RequestMapping("/auth/delCashier")
    public R delCashier(@RequestParam String mobilephone) {
        try {
            cashiersService.updateCashierState("2", mobilephone);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("删除收款员失败");
        }


    }

    /**
     * 修改收款员信息
     */
    @ResponseBody
    @RequestMapping("/auth/modifyCashier")
    public R modifyCashier(@RequestParam String name, String mobilephone) {
        logger.info("name==" + name);
        int result = cashiersService.modifyCashier(name, mobilephone);
        if (result > 0) {
            return R.ok();
        } else {
            return R.error();
        }

    }

    /**
     * 查看收款码详情
     *
     * @param codeNo 收款码编号
     */
    @ResponseBody
    @RequestMapping(value = "/auth/viewCodeDetails", method = RequestMethod.GET)
    public ModelAndView viewCodeDetails(@RequestParam String codeNo, HttpServletRequest request, ModelMap map) {
        QRCode qrcode = codeService.findQRCodeByCodeno(codeNo);
        map.put("qrcode", qrcode);
        return new ModelAndView("qrCodeDetails.jsp");
    }

    /**
     * 删除收款码（逻辑删除）
     *
     * @param codeNo
     * @return
     */
    @ResponseBody
    @RequestMapping("/auth/deleteQrCode")
    public R deleteQrCode(@RequestParam String codeNo) {
        try {
            QRCode qrcode = codeService.findCodeDetailsByCodeno(codeNo);
            if (qrcode != null && "0".equals(qrcode.getCodeStatus())) {//是默认的生成的不能删
                return R.error("该二维码为管理员的，无法进行删除。");
            } else {
                codeService.updateQrCode(codeNo, "1");//0,为删除 1，已删除
            }
            return R.ok();
        } catch (Exception e) {
            logger.info("删除失败" + e.getMessage());
            e.printStackTrace();
            return R.error("删除失败");
        }
    }


    /**
     * 生成二维码
     *
     * @param name   请输入收款码名称
     * @param userId 请选择所属用户(用户名称+"/"+手机号码)
     * @return
     */
    @ResponseBody
    @RequestMapping("/auth/createQrCode")
    public R createQrCode(@RequestParam String name, @RequestParam Long userId, @RequestParam Long bankId) {
        try {
            ///查询当前用户再该用途下是否创建过二维码
            QRCode qRCode = new QRCode();
            qRCode.setUserId(userId);//用户ID
            qRCode.setBankId(bankId);//银行（渠道商配置）
            List<QRCode> qRCodelist = qRCodeService.queryQRCodeList(qRCode);
            if (qRCodelist != null && qRCodelist.size() != 0) {
                return R.error("该用户在该用途下已创建二维码，无需重复创建!");
            }
            //查询银行信息（即支付渠道商信息）
            BankInfo bankInfo = bankInfoService.querryBankInfoById(bankId);
            if (bankInfo != null && StringUtil.isNotEmpty(bankInfo.getMerchantNo())) {
                String date = DateUtils.format(new Date(), "yyyyMMdd");
                String random = RandomStringUtils.randomNumeric(6);
                String codeNo = date + random;
                StringBuffer qrurl = new StringBuffer();
                //下载时访问地址Constant.DOMAINURL +
                qrurl.append("merchant/userAgent");//http://www.***.cn/wechat/merchant/userAgent
                qrurl.append("?merchantNo=" + bankInfo.getMerchantNo());// 商户号
                logger.info("qrurl---------" + qrurl);
                qRCode.setCodeName(name);         //收款码名称
                qRCode.setCodeNo(codeNo);         //收款码编号
                qRCode.setMerchantId(bankInfo.getMerchantNo()); //商户编号
                qRCode.setUserId(userId);         //用户ID
                qRCode.setUrl(qrurl.toString());  //访问路径
                qRCode.setBankId(bankId);///
                qRCodeService.insertQrCode(qRCode);  //保存二维码信息
                return R.ok();
            } else {
                return R.error("该用途下渠道商信息错误!");
            }
        } catch (Exception e) {
            logger.error("生成二维码异常", e);
            return R.error("生成二维码失败!");
        }
    }

    /**
     * 查看二维码
     *
     * @param codeNo   String 收款码编号
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     */
    @RequestMapping("/lookqrCode")
    public void lookqrCode(@RequestParam String codeNo, HttpServletRequest request, HttpServletResponse response) {
        QRCode qRCode = qRCodeService.findCodeDetailsByCodeno(codeNo);
        if (qRCode != null) {
            String url = qRCode.getUrl() + "&codeNo=" + codeNo;//商户编号  +  收款码编号
            String merchantNo = qRCode.getMerchantId();
            response.setContentType("image/jpeg");
            try {
                com.ipay.core.QRCode.printQRCodeByLogo(response.getOutputStream(), url, codeNo, merchantNo);
            } catch (IOException e) {
                logger.error("查看二维码输出异常：", e);
            }
        }
    }

    /**
     * 新查看二维码
     *
     * @param codeNo   String 收款码编号
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     */
    @RequestMapping("/lookqrNewCode")
    public void lookqrNewCode(@RequestParam String codeNo, HttpServletRequest request, HttpServletResponse response) {
        QRCode qRCode = qRCodeService.findCodeDetailsByCodeno(codeNo);
        if (qRCode != null) {
            String url = wechat.getBaseUrl() + qRCode.getUrl() + "&codeNo=" + codeNo;//商户编号  +  收款码编号 ///Constant.DOMAINURL_HTTPS
            String merchantNo = qRCode.getMerchantId();
            response.setContentType("image/jpeg");
            try {
                MerchantInfo merchantInfo = applyService.querryMerchantInfoByMerchantNo(merchantNo);
                if (merchantInfo != null && StringUtil.isNotEmpty(merchantInfo.getShopname())) {
                    File fileLogo = new File(wechat.getUploadImgPath() + merchantInfo.getLogo());//公司logo
                    String head = merchantInfo.getShopname();//公司名称
                    com.ipay.core.QRCode.printQRCodeByLogo(response.getOutputStream(), fileLogo, head, url, codeNo);
                }else{
                    com.ipay.core.QRCode.printErrorImg(response.getOutputStream(), "公司logo暂时未上传,联系管理员上传");
                }
            } catch (IOException e) {
                logger.error("查看二维码输出异常：", e);
            }
        } else {
            logger.info("=========获取二维码信息错误===========" + codeNo);
            try {
                com.ipay.core.QRCode.printErrorImg(response.getOutputStream(), "收款二维码参数错误");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 固定金额 查看二维码
     *
     * @param payId   String 收款码编号
     * @param codeNo   String 收款码编号
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     */
    @RequestMapping("/lookFixedMoneyCode")
    public void lookFixedMoneyCode(@RequestParam String payId,@RequestParam String codeNo, HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("image/jpeg");
        try {
            ///根据payId查询固定金额支付相关参数
            MerchantPayParameter merchantPay = merchantPayParameterService.queryObject(payId);
            if (merchantPay != null && StringUtil.isNotEmpty(merchantPay.getMerchantNo())) { //商户编号不能为空
                if (StringUtil.isNotEmpty(merchantPay.getCodeNo()) && codeNo.equals(merchantPay.getCodeNo())) { ///支付  收款员编号与查询的参数里的收款员编号是否相符
                    String postUrl = wechat.getBaseUrl() + "merchant/payFMGateway?payId=" + payId + "&codeNo=" + codeNo + "&merchantNo=" + merchantPay.getMerchantNo();
                    logger.info("====postUrl:" + postUrl);
                    MerchantInfo merchantInfo = applyService.querryMerchantInfoByMerchantNo(merchantPay.getMerchantNo());
                    if (merchantInfo != null && StringUtil.isNotEmpty(merchantInfo.getShopname())) {
                        File fileLogo = new File(wechat.getUploadImgPath() + merchantInfo.getLogo());//公司logo
                        String head = merchantInfo.getShopname();//公司名称
                        com.ipay.core.QRCode.printQRCodeByLogo(response.getOutputStream(), fileLogo, head, postUrl, codeNo);
                    }else{
                        com.ipay.core.QRCode.printErrorImg(response.getOutputStream(), "公司logo暂时未上传,联系管理员上传");
                    }
                }else{
                    com.ipay.core.QRCode.printErrorImg(response.getOutputStream(), "收款员参数错误");
                }
            }else{
                com.ipay.core.QRCode.printErrorImg(response.getOutputStream(), "商户参数错误");
            }
        } catch (IOException e) {
            logger.error("查看二维码输出异常：", e);
        }
    }

    /**
     * 查看图片
     *
     * @param filePath String 图片路径
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     *                 127.0.0.1:8081/lookImage?filePath=F:\qycache\88888889\593703.jpg
     */
    @RequestMapping("/lookImage")
    public void lookImage(@RequestParam String filePath, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtil.isNotEmpty(filePath)) {
            String imgSize = request.getParameter("imgSize");//图片尺寸大小  100x100
            String realPath = request.getSession().getServletContext().getRealPath("/");
            if (StringUtil.isNotEmpty(imgSize)) {
                filePath = wechat.getUploadImgPath() + filePath;
                String retufilePath = new Utils().resize(filePath, imgSize, realPath);
                Utils.look(retufilePath, response);
            } else {
                ///判断文件是否存在
                File file = new File(wechat.getUploadImgPath() + filePath);
                if (file.exists()) {
                    Utils.look(wechat.getUploadImgPath() + filePath, response);
                } else {
                    ///todo 默认图片处理  带修改
                    String retufilePath = realPath + Constant.DEFAULT_PNG;
                    Utils.look(retufilePath, response);
                }
            }
        }
    }

    /**
     * 查看商户入驻及服务协议
     */
    @ResponseBody
    @RequestMapping("/auth/serviceAgreement")
    public ModelAndView serviceAgreement() {
        return new ModelAndView("serviceAgreement.jsp");
    }

    /**
     * 查看商户入驻及服务协议
     */
    @ResponseBody
    @RequestMapping("/auth/agreement")
    public ModelAndView agreement() {
        return new ModelAndView("agreement.jsp");
    }

    /**
     * 查看商户入驻及服务协议
     */
    @ResponseBody
    @RequestMapping("/auth/usermanual")
    public ModelAndView usermanual() {
        return new ModelAndView("usermanual.html");
    }

    /**
     * 修改邮箱
     *
     * @param email 邮箱
     * @return
     */
    @ResponseBody
    @RequestMapping("/auth/updateEmail")
    public R updateEmail(@RequestParam String merchantNo, @RequestParam String email) {
        applyService.updateEmail(merchantNo, email);
        return R.ok();
    }


    /**
     * 分享出去的二维码  进入地址
     * /auth/shareCode/20171031205938
     *
     * @param model
     * @param requesturl
     * @return
     */
    @RequestMapping(value = "/auth/shareCode/{codeNo}", method = RequestMethod.GET)
    public ModelAndView shareCode(ModelMap model, HttpServletRequest requesturl, @PathVariable("codeNo") String codeNo) {
        String ticket = jedies.getValue(JedisKeyPrefix.JEDIS_KEY_PREFIX_WECHAT_TOKEN, "jsapi_ticket");
        //String url =Constant.DOMAINURL + "order/testScanCode";
        String url = requesturl.getRequestURL().toString();
        System.out.println("url============" + url);
        if (!url.startsWith("https:")) {
            url = url.replaceAll("http", "https");
        }
        System.out.println("url---------------" + url);
        Map<String, String> ret = WxJSUtil.sign(url, ticket);
        for (Map.Entry entry : ret.entrySet()) {
            System.out.println(entry.getKey() + "=" + entry.getValue());
            model.addAttribute(entry.getKey().toString(), entry.getValue());
        }
        model.addAttribute("appId", wechat.getAppId());///微信appid
        model.addAttribute("codeNo", codeNo);///二维码编号
        model.addAttribute("baseUrl", wechat.getBaseUrl());
        if (StringUtil.isEmpty(codeNo)) {
            model.addAttribute("errorMesage", "二维码编号错误");
            return new ModelAndView("/pay/payError.jsp").addObject(model);
        } else {
            QRCode qrcode = codeService.findQRCodeByCodeno(codeNo);
            if (qrcode != null && StringUtil.isNotEmpty(qrcode.getMerchantId())) {
                MerchantInfoEntity merchantInfo = merchantInfoService.queryObject(qrcode.getMerchantId());
                model.addAttribute("title", qrcode.getCodeName());//分享标题
                model.addAttribute("desc", "此二维码是：" + merchantInfo.getShopName() + "," + qrcode.getCodeName() + "的收款二维码！编号：" + qrcode.getCodeNo());//分享描述
                model.addAttribute("imgUrl", merchantInfo.getLogo());//分享图标
                //https://www.***.cn/wechat/lookImage?filePath="+logo+"&imgSize=400x100
            }
        }
        return new ModelAndView("/share/shareCode.jsp").addObject(model);
    }

}
